<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/xizhongren8980/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/xizhongren8980/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/xizhongren8980/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/xizhongren8980/images/logo.svg" color="#222">

<link rel="stylesheet" href="/xizhongren8980/css/main.css">


<link rel="stylesheet" href="/xizhongren8980/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/xizhongren8980/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="什么是Cookie？ Cookie是服务器通知客户端保存键值对的一种技术。  客户端有了Cookie后，每次请求都发送给服务器。">
<meta property="og:type" content="article">
<meta property="og:title" content="【JavaWeb】学习笔记之Cookie">
<meta property="og:url" content="https://gitee.com/xizhongren8980/xizhongren8980.git/2020/05/19/%E3%80%90JavaWeb%E3%80%91%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%E4%B9%8BCookie/index.html">
<meta property="og:site_name" content="一杯茶一包烟，一个BUG改一天">
<meta property="og:description" content="什么是Cookie？ Cookie是服务器通知客户端保存键值对的一种技术。  客户端有了Cookie后，每次请求都发送给服务器。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/image-20200519161547852.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/image-20200519161816613.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/image-20200519202215657.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/image-20200519204339310.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/image-20200519231957836.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/image-20200519232057211.png">
<meta property="article:published_time" content="2020-05-19T15:29:46.559Z">
<meta property="article:modified_time" content="2020-05-19T15:36:49.888Z">
<meta property="article:author" content="MisterTian">
<meta property="article:tag" content="Cookie">
<meta property="article:tag" content="学习笔记">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/image-20200519161547852.png">

<link rel="canonical" href="https://gitee.com/xizhongren8980/xizhongren8980.git/2020/05/19/%E3%80%90JavaWeb%E3%80%91%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%E4%B9%8BCookie/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>【JavaWeb】学习笔记之Cookie | 一杯茶一包烟，一个BUG改一天</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/xizhongren8980/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">一杯茶一包烟，一个BUG改一天</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">收藏永不停止，学习永不开始</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/xizhongren8980/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/xizhongren8980/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/xizhongren8980/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/xizhongren8980/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/xizhongren8980/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/xizhongren8980/xizhongren8980.git/2020/05/19/%E3%80%90JavaWeb%E3%80%91%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%E4%B9%8BCookie/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/xizhongren8980/images/head.jpg">
      <meta itemprop="name" content="MisterTian">
      <meta itemprop="description" content="一个小菜鸟">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一杯茶一包烟，一个BUG改一天">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          【JavaWeb】学习笔记之Cookie
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-05-19 23:29:46 / 修改时间：23:36:49" itemprop="dateCreated datePublished" datetime="2020-05-19T23:29:46+08:00">2020-05-19</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/xizhongren8980/categories/JavaWeb/" itemprop="url" rel="index"><span itemprop="name">JavaWeb</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="什么是Cookie？"><a href="#什么是Cookie？" class="headerlink" title="什么是Cookie？"></a>什么是Cookie？</h3><ul>
<li><p>Cookie是服务器通知客户端保存键值对的一种技术。</p>
</li>
<li><p>客户端有了Cookie后，每次请求都发送给服务器。<a id="more"></a></p>
</li>
<li><p>每个Cookie的大小不能超过4kb。</p>
</li>
</ul>
<h3 id="Cookie的创建："><a href="#Cookie的创建：" class="headerlink" title="Cookie的创建："></a>Cookie的创建：</h3><ul>
<li><p>在服务器创建Cookie对象</p>
<figure class="highlight ebnf"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">Cookie cookie</span> = new Cookie(<span class="string">"key1"</span>,<span class="string">"value1"</span>);</span><br></pre></td></tr></table></figure>
</li>
<li><p>通知客户端保存Cookie</p>
<figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">resp.add<span class="constructor">Cookie(<span class="params">cookie</span>)</span>;</span><br></pre></td></tr></table></figure>
</li>
<li><p>创建成功的Cookie对象通过响应头 <code>Set-Cookie</code> 通知客户端保存<code>Cookie</code></p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Set-Cookie: <span class="attribute">key1</span>=value1</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/image-20200519161547852.png" alt="image-20200519161547852"></p>
</li>
<li><p>客户端收到响应后，发现有<code>Set-Cookie</code> 响应头，就去看一下，有没有这个Cookie，没有就创建，有就修改。</p>
</li>
</ul>
<p><img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/image-20200519161816613.png" alt="image-20200519161816613"></p>
<ul>
<li><p>CookieServlet程序中的代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CookieServlet</span> <span class="keyword">extends</span> <span class="title">BaseServlet</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">createCookie</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</span><br><span class="line">        <span class="comment">// 创建cookie对象</span></span><br><span class="line">        Cookie cookie = <span class="keyword">new</span> Cookie(<span class="string">"key1"</span>, <span class="string">"value1"</span>);</span><br><span class="line">        <span class="comment">// 通知客户端保存cookie</span></span><br><span class="line">        resp.addCookie(cookie);</span><br><span class="line"></span><br><span class="line">        resp.getWriter().write(<span class="string">"cookie创建成功"</span>);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h3 id="服务器获取Cookie："><a href="#服务器获取Cookie：" class="headerlink" title="服务器获取Cookie："></a>服务器获取Cookie：</h3><ul>
<li><p>服务器端通过请求获得全部cookie信息</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Cookie[] cookies = req.getCookies();</span><br></pre></td></tr></table></figure>
</li>
<li><p>客户端有了Cookie，通过请求头 Cookie ：××=×× 把全部Cookie信息发送给服务器。</p>
<img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/image-20200519202215657.png" alt="image-20200519202215657" style="zoom:50%;" />
</li>
<li><p>获取指定 <code>key</code> 的 <code>cookie</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**查找指定名称的cookie对象</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Param</span> [name, cookies]</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> javax.servlet.http.Cookie</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Cookie <span class="title">findCookies</span><span class="params">(String name, Cookie[] cookies)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (name == <span class="keyword">null</span> || cookies == <span class="keyword">null</span> || cookies.length == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">for</span> (Cookie cookie : cookies) &#123;</span><br><span class="line">            <span class="keyword">if</span> (name.equals(cookie.getName())) &#123;</span><br><span class="line">                <span class="keyword">return</span> cookie;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>cookieServlet程序中的代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">getCookie</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</span><br><span class="line">        Cookie[] cookies = req.getCookies();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (Cookie cookie: cookies</span><br><span class="line">             ) &#123;</span><br><span class="line">            resp.getWriter().write(<span class="string">"Cookie["</span> + cookie.getName() + <span class="string">"="</span> + cookie.getValue()+ <span class="string">"]&lt;br/&gt;"</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        Cookie iwantCookie = CookieUtils.findCookies(<span class="string">"key1"</span>, cookies);</span><br><span class="line">        <span class="keyword">if</span> (iwantCookie != <span class="keyword">null</span>) &#123;</span><br><span class="line">            resp.getWriter().write(<span class="string">"找到了需要的cookie"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>



</li>
</ul>
<p><img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/image-20200519204339310.png" alt="image-20200519204339310"></p>
<h3 id="Cookie值的修改"><a href="#Cookie值的修改" class="headerlink" title="Cookie值的修改"></a>Cookie值的修改</h3><ul>
<li><p>方案一：</p>
<ol>
<li>先创建一个要修改的同名的Cookie对象</li>
<li>在构造器中，同时赋予新的Cookie值</li>
<li>调用 <code>resp.addCookie(Cookie)</code> </li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">updateCookie</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</span><br><span class="line">        <span class="comment">// 先创建一个要修改的Cookie对象,并且在构造器中赋予新的值</span></span><br><span class="line">        Cookie cookie = <span class="keyword">new</span> Cookie(<span class="string">"key1"</span>, <span class="string">"newValue1"</span>);</span><br><span class="line">        <span class="comment">// 调用resp.addCookie(cookie) 通知客户端保存修改</span></span><br><span class="line">        resp.addCookie(cookie);</span><br><span class="line"></span><br><span class="line">        resp.getWriter().write(<span class="string">"key1的Cookie值已经修改好了"</span>);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>



</li>
</ul>
<ul>
<li><p>方案二：</p>
<ol>
<li>先查找到需要的Cookie对象</li>
<li>调用 <code>setValue</code> 方法赋予新的Cookie值</li>
<li>调用 <code>resp.addCookie()</code> 通知客户端保存修改</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">updateCookie</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</span><br><span class="line"><span class="comment">//        // 方案一</span></span><br><span class="line"><span class="comment">//        // 先创建一个要修改的Cookie对象,并且在构造器中赋予新的值</span></span><br><span class="line"><span class="comment">//        Cookie cookie = new Cookie("key1", "newValue1");</span></span><br><span class="line"><span class="comment">//        // 调用resp.addCookie(cookie) 通知客户端保存修改</span></span><br><span class="line"><span class="comment">//        resp.addCookie(cookie);</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 方案二</span></span><br><span class="line">        <span class="comment">// 先查找到需要修改的Cookie对象</span></span><br><span class="line">        Cookie cookie = CookieUtils.findCookies(<span class="string">"key1"</span>, req.getCookies());</span><br><span class="line">        <span class="comment">// 调用setValue()方法赋予新的值</span></span><br><span class="line">        cookie.setValue(<span class="string">"newKey11"</span>);</span><br><span class="line">        <span class="comment">// 调用resp.addCookie()通知客户端保存修改</span></span><br><span class="line">        resp.addCookie(cookie);</span><br><span class="line">        resp.getWriter().write(<span class="string">"key1的Cookie值已经修改好了"</span>);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h3 id="Cookie-生命控制"><a href="#Cookie-生命控制" class="headerlink" title="Cookie 生命控制"></a>Cookie 生命控制</h3><p>Cookie的生命周期指的就是如何管理Cookie什么时候被销毁（删除）。</p>
<ul>
<li>setMaxAge()<ul>
<li>正数：表示在指定的秒数后过期</li>
<li>负数：表示浏览器关闭，Cookie就会被删除（默认值是-1）</li>
<li>零：表示马上删除Cookie</li>
</ul>
</li>
</ul>
<h3 id="Cookie-有效路径-Path-的设置"><a href="#Cookie-有效路径-Path-的设置" class="headerlink" title="Cookie 有效路径 Path 的设置"></a>Cookie 有效路径 Path 的设置</h3><p>Cookie的path属性可以有效的过滤哪些Cookie可以发送给服务器。</p>
<p>path 属性是通过请求的地址来进行有效的过滤。</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">CookieA		<span class="attribute">path</span>=/工程路径</span><br><span class="line">CookieB		<span class="attribute">path</span>=/工程路径/abc</span><br></pre></td></tr></table></figure>

<p>请求地址如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http:<span class="comment">//ip:port/工程路径/a.html</span></span><br></pre></td></tr></table></figure>

<p>CookieA    发送</p>
<p>CookieB    不发送</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http:<span class="comment">//ip:port/工程路径/abc/a.html</span></span><br></pre></td></tr></table></figure>

<p>CookieA    发送</p>
<p>CookieB    发送</p>
<ul>
<li>代码测试：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">testPath</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</span><br><span class="line">        Cookie cookie = <span class="keyword">new</span> Cookie(<span class="string">"path"</span>, <span class="string">"path"</span>);</span><br><span class="line">        <span class="comment">// getContextPath() ===&gt;&gt;&gt;得到的是工程路径</span></span><br><span class="line">        cookie.setPath(req.getContextPath() + <span class="string">"/abc"</span>);  <span class="comment">///===&gt;&gt;&gt;  /工程路径/abc</span></span><br><span class="line">        resp.addCookie(cookie);</span><br><span class="line">        resp.getWriter().write(<span class="string">"创建了一个带有Path路径的Cookie"</span>);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/image-20200519231957836.png" alt="image-20200519231957836" style="zoom:50%;" />

<img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/image-20200519232057211.png" alt="image-20200519232057211" style="zoom:50%;" />

<p>从以上截图可以看出，cookie已经发送，但是由于path属性匹配，cookie被浏览器拦截过滤了。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/xizhongren8980/tags/Cookie/" rel="tag"># Cookie</a>
              <a href="/xizhongren8980/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag"># 学习笔记</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/xizhongren8980/2020/05/15/560.%E5%92%8C%E4%B8%BAK%E7%9A%84%E5%AD%90%E6%95%B0%E7%BB%84/" rel="prev" title="【LeetCode】560.和为K的子数组">
      <i class="fa fa-chevron-left"></i> 【LeetCode】560.和为K的子数组
    </a></div>
      <div class="post-nav-item">
    <a href="/xizhongren8980/2020/05/21/%E3%80%90JavaWeb%E3%80%91%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%E4%B9%8B-Session-%E4%BC%9A%E8%AF%9D/" rel="next" title="【JavaWeb】学习笔记之 Session 会话">
      【JavaWeb】学习笔记之 Session 会话 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#什么是Cookie？"><span class="nav-number">1.</span> <span class="nav-text">什么是Cookie？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Cookie的创建："><span class="nav-number">2.</span> <span class="nav-text">Cookie的创建：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#服务器获取Cookie："><span class="nav-number">3.</span> <span class="nav-text">服务器获取Cookie：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Cookie值的修改"><span class="nav-number">4.</span> <span class="nav-text">Cookie值的修改</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Cookie-生命控制"><span class="nav-number">5.</span> <span class="nav-text">Cookie 生命控制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Cookie-有效路径-Path-的设置"><span class="nav-number">6.</span> <span class="nav-text">Cookie 有效路径 Path 的设置</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="MisterTian"
      src="/xizhongren8980/images/head.jpg">
  <p class="site-author-name" itemprop="name">MisterTian</p>
  <div class="site-description" itemprop="description">一个小菜鸟</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/xizhongren8980/archives/">
        
          <span class="site-state-item-count">57</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/xizhongren8980/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/xizhongren8980/tags/">
          
        <span class="site-state-item-count">101</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://mistertian8980.github.io/" title="https:&#x2F;&#x2F;mistertian8980.github.io&#x2F;" rel="noopener" target="_blank">Github博客</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">MisterTian</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script size="300" alpha="0.6" zIndex="-1" src="/xizhongren8980/lib/canvas-ribbon/canvas-ribbon.js"></script>
  <script src="/xizhongren8980/lib/anime.min.js"></script>
  <script src="/xizhongren8980/lib/velocity/velocity.min.js"></script>
  <script src="/xizhongren8980/lib/velocity/velocity.ui.min.js"></script>

<script src="/xizhongren8980/js/utils.js"></script>

<script src="/xizhongren8980/js/motion.js"></script>


<script src="/xizhongren8980/js/schemes/pisces.js"></script>


<script src="/xizhongren8980/js/next-boot.js"></script>


  <script defer src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/three.min.js"></script>
    <script defer src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/canvas_lines.min.js"></script>


  




  
<script src="/xizhongren8980/js/local-search.js"></script>













  

  

</body>
</html>
